package com.jade.framework.base.security;

import java.io.Serializable;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * ActionPermissionCollection.
 *
 * @author dwzhang
 * @version 1.0 13-4-18 上午9:22
 */
public class ActionPermissionCollection extends PermissionCollection implements Serializable
{
    // Not serialized; see serialization section at end of class
    private transient List<Permission> perms;

    public ActionPermissionCollection()
    {
        perms = new ArrayList<Permission>();
    }

    /**
     * Adds a permission to the FilePermissions. The key for the hash is
     * permission.path.
     *
     * @param permission the Permission object to add.
     * @throws IllegalArgumentException - if the permission is not a
     *                                  FilePermission
     * @throws SecurityException        - if this FilePermissionCollection object
     *                                  has been marked readonly
     */

    public void add(Permission permission)
    {
        if (!(permission instanceof ActionPermission)) {
            throw new IllegalArgumentException("invalid permission: " + permission);
        }
        if (isReadOnly()) {
            throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
        }

        // No need to synchronize because all adds are done sequentially
        // before any implies() calls
        perms.add(permission);
    }

    /**
     * Check and see if this set of permissions implies the permissions
     * expressed in "permission".
     *
     * @param permission the Permission object to compare
     * @return true if "permission" is a proper subset of a permission in
     *         the set, false if not.
     */

    public boolean implies(Permission permission)
    {
        if (!(permission instanceof ActionPermission)) {
            return false;
        }

        int len = perms.size();
        for (int i = 0; i < len; i++) {
            ActionPermission x = (ActionPermission)perms.get(i);
            if (x.implies(permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns an enumeration of all the FilePermission objects in the
     * container.
     *
     * @return an enumeration of all the FilePermission objects.
     */

    public Enumeration<Permission> elements()
    {
        // Convert Iterator into Enumeration
        return Collections.enumeration(perms);
    }
}
